package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var file *os.File
var err error

func init() {
	CurExeDir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	//	/home/nvidia/Synjones/zll
	//  F:\workwork\2019OpenSource\src\gLogService
	fmt.Printf("hello gLogService, curPath = %s \n", CurExeDir)
	// tmpCur, tmpFile := filepath.Split(CurExeDir)
	// fmt.Printf("ddd:%s - %s \n", tmpCur, tmpFile)

	//	/home/nvidia/Synjones/zll/Log
	//  F:\workwork\2019OpenSource\src\gLogService\Log
	CurLogDir = filepath.Join(CurExeDir, "Log")
	if _, err := os.Stat(CurLogDir); err != nil {
		os.MkdirAll(CurLogDir, 0711)
	}
	timeStr := time.Now().Format("20060102")

	// /home/nvidia/Synjones/zll/Log/20190506.log
	// F:\workwork\2019OpenSource\src\gLogService\Log\20190506.log
	curLogFileDir := filepath.Join(CurLogDir, timeStr) + ".log"
	fmt.Printf("curLogPathFile = %s \n", curLogFileDir)
	file, err = os.OpenFile(curLogFileDir, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(file)
}

func recvLoggerInfo(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	var dat map[string]interface{}
	resultmap := make(map[string]interface{})
	resultmap["cmd"] = "writelog"
	if err := json.Unmarshal(body, &dat); err == nil {
		resultmap["result"] = "ok"
		filesync()
		log.SetPrefix("[" + dat["level"].(string) + "]")
		log.Println(dat["desc"])
	} else {
		resultmap["result"] = "fail"
	}

	sendResult, _ := json.Marshal(resultmap)
	w.Header().Set("Content-Type", "application/json;charset=UTF-8")
	w.Write(sendResult)

	// nlogNum++
	// fmt.Printf("Logger thread id= %d, num=%d\n", windows.GetCurrentThreadId(), nlogNum)
}

func loggertest(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	// body_str := string(body)
	// fmt.Println(body_str)
	var u MsgData
	resultmap := make(map[string]interface{})
	resultmap["cmd"] = "writelog"
	if err := json.Unmarshal(body, &u); err == nil {
		resultmap["result"] = "ok"
		resultmap["level"] = u.Level
		fmt.Printf("recv desc= %s \n", u.Desc)
	} else {
		resultmap["result"] = "fail"
	}
	sendResult, _ := json.Marshal(resultmap)
	w.Write(sendResult)
	// w.Write([]byte("来自 golang http server 的问候"))

	// fmt.Printf("current thread 2id= %d\n", windows.GetCurrentThreadId())
}

func filesync() {
	timeStr := time.Now().Format("20060102")
	filePathName := filepath.Join(CurLogDir, timeStr) + ".log"
	// filePathName := "./Log/" + timeStr + ".log"
	// fmt.Println(filePathName)
	if _, err := os.Stat(filePathName); err != nil {
		if os.IsNotExist(err) {
			file.Close()
			file, err = os.OpenFile(filePathName, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
			if err != nil {
				log.Fatal(err)
			}
			log.SetOutput(file)
		}
	}

	dir, err := ioutil.ReadDir(CurLogDir)
	if err != nil {
		return
	}

	for _, fi := range dir {
		if fi.IsDir() {

		} else {
			ok := strings.HasSuffix(fi.Name(), ".log")
			if ok {
				curTime := time.Now()
				todayTime := curTime.Format("20060102.log")
				beforeTime1 := curTime.AddDate(0, 0, -1).Format("20060102.log")
				beforeTime2 := curTime.AddDate(0, 0, -2).Format("20060102.log")
				beforeTime3 := curTime.AddDate(0, 0, -3).Format("20060102.log")
				beforeTime4 := curTime.AddDate(0, 0, -4).Format("20060102.log")
				beforeTime5 := curTime.AddDate(0, 0, -5).Format("20060102.log")
				beforeTime6 := curTime.AddDate(0, 0, -6).Format("20060102.log")
				curFilename := fi.Name()
				if curFilename != todayTime && curFilename != beforeTime1 && curFilename != beforeTime2 && curFilename != beforeTime3 &&
					curFilename != beforeTime4 && curFilename != beforeTime5 && curFilename != beforeTime6 {
					os.Remove(filepath.Join(CurLogDir, fi.Name()))
				}
			}
		}
	}
}
